﻿package com.crayon.ui
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.net.navigateToURL;
	import flash.events.ContextMenuEvent;
	import flash.net.URLRequest;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;

	/**
	 * ...
	 * @author 蜡笔
	 */
	public class RightMenu
	{
		private static var _instance:RightMenu;

		private var _contextMenu:ContextMenu;
		private var _contextMenuItem:ContextMenuItem;
		private var _functionList:Vector.<Function>;
		private var _itemList:Vector.<ContextMenuItem>;

		public function RightMenu(single:SingletonForcer)
		{
			_contextMenu = new ContextMenu();
			_functionList = new Vector.<Function>();
			_itemList = new Vector.<ContextMenuItem>();
		}
		
		public static function getInstance():RightMenu
		{
			if (_instance == null)
			{
				RightMenu._instance = new RightMenu(new SingletonForcer());
			}
			return RightMenu._instance;
		}

		public function hideDefaultMenu():void
		{
			_contextMenu.hideBuiltInItems();
		}
		
		public function init(value:DisplayObjectContainer):void
		{
			value.contextMenu = _contextMenu;
			RightMenu.getInstance().addItem("Design by：蜡笔",true, crayonSite);
		}
		
		public function addSeparatorBefore(index:int):void
		{
			if (index > _contextMenu.customItems.length)
				return;
				//throw Error("The index is out of length of MenuItem");

			if (--index < 1)
				return;
			var item:ContextMenuItem = _contextMenu.customItems[index] as ContextMenuItem;
			item.separatorBefore = true;
		}

		public function addItem(text:String, enabled:Boolean = true, fun:Function = null):void
		{
			_contextMenuItem = new ContextMenuItem(text, false, enabled);
			_contextMenuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onItemSelect);

			_contextMenu.customItems.push(_contextMenuItem);
			_functionList.push(fun);
		}

		private function onItemSelect(cme:ContextMenuEvent):void
		{
			var itemIndex:int = _contextMenu.customItems.indexOf(cme.target);
			var itemFunction:Function = _functionList[itemIndex];
			if (itemFunction != null)
				itemFunction();
		}

		private function crayonSite():void
		{
			navigateToURL(new URLRequest("http://hi.baidu.com/蜡笔工作室"));
		}

	}

}

class SingletonForcer
{
}